//
//  AudioVerifyPwdViewController.m
//  TestAispeech
//
//  Created by shaowei on 13-9-8.
//  Copyright (c) 2013年 LianZhan. All rights reserved.
//

#import "AudioVerifyPwdViewController.h"
#import "AudioSetPwdViewController.h"

@interface AudioVerifyPwdViewController ()

@end

@implementation AudioVerifyPwdViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    if (![AudioManager isHaveAudioPwd]) {
        ALERT_VIEW(@"您还未设置过声音密码", @"开始设置声音密码");
        [self performSegueWithIdentifier:@"AudioSetPwdViewController" sender:nil];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    Block_release(_completeHandle);
    [super dealloc];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    __block AudioVerifyPwdViewController *tempSelf = self;
    if ([segue.identifier isEqualToString:@"AudioSetPwdViewController"]) {
        AudioSetPwdViewController *tempVC = (AudioSetPwdViewController *)segue.destinationViewController;
        [tempVC setCompleteHandle:^(BOOL success) {
            if (success) {
                //回到前台主线程执行
                dispatch_async(dispatch_get_main_queue(), ^{
                    [tempSelf.presentedViewController dismissModalViewControllerAnimated:YES];
                }) ;
            }
        }];
    }
    
}

#pragma mark - #pragma mark - AiRecognizerDelegate
/**
 *	@brief	引擎收到了评测结果
 *
 *	@param 	engine      引擎对象
 *	@param 	recordId 	录音流ID
 *	@param 	jsonString 	服务端返回JSON结果
 */
-(void)aiSpeechEngine:(AiSpeechEngine *)engine didReceive:(NSString *)recordId responseJson:(NSString *)jsonString{
    NSLog(@"receive-json:\n%@",jsonString) ;
    
    NSString *resultString = [self getRecognizerStringFromString:jsonString];
    if (resultString) {
        [self.textViewOfResult setText:resultString];
        [self checkPwd:resultString];
    }
}

#pragma mark - custom

- (void)checkPwd:(NSString *)pwdString {
    if (pwdString.length) {
        BOOL result = [AudioManager verifyAudioPwdWithString:pwdString];
        if (result) {
            ALERT_VIEW(@"恭喜,声音密码验证通过！", nil);
        }else{
            ALERT_VIEW(@"Sorry,密码验证失败", nil);
        }
        
        //回调
        if (_completeHandle) {
            _completeHandle(result);
        }
        
    }else{
        ALERT_VIEW(@"密码不能为空,请开始声音识别", nil);
    }
}
@end
